import 'package:flutter/material.dart';

/// 可拖拽组件
class DraggableWidget extends StatefulWidget {
  final Widget child;
  final Offset initialPosition;
  final VoidCallback? onTap;

  const DraggableWidget({
    super.key,
    required this.child,
    this.initialPosition = const Offset(30, 100), // 默认初始位置：左边30，顶部100
    this.onTap,
  });

  @override
  _DraggableWidgetState createState() => _DraggableWidgetState();
}

class _DraggableWidgetState extends State<DraggableWidget> {
  late Offset _offset;
  final _key = GlobalKey(); // 用于获取子组件尺寸
  Size _childSize = Size.zero;

  @override
  void initState() {
    super.initState();
    _offset = widget.initialPosition; // 设置初始位置
    // 在第一帧渲染后获取子组件尺寸
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final context = _key.currentContext;
      if (context != null) {
        final renderBox = context.findRenderObject() as RenderBox?;
        if (renderBox != null) {
          setState(() {
            _childSize = renderBox.size; // 获取子组件的实际尺寸
          });
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // 获取屏幕尺寸用于边界处理
    final screenSize = MediaQuery.of(context).size;

    return Positioned(
      left: _offset.dx,
      top: _offset.dy,
      child: GestureDetector(
        onPanUpdate: (details) {
          setState(() {
            _offset += details.delta;
            // 边界处理：限制悬浮球在屏幕范围内，基于子组件尺寸
            _offset = Offset(
              _offset.dx.clamp(0, screenSize.width - _childSize.width),
              _offset.dy.clamp(0, screenSize.height - _childSize.height),
            );
          });
        },
        onTap: widget.onTap, // 处理点击事件
        child: Container(
          key: _key, // 绑定 GlobalKey 以获取尺寸
          child: widget.child,
        ),
      ),
    );
  }
}
